<template>
  <el-dialog
    v-model="state.open"
    :title="state.title"
    :width="447"
    :before-close="cancel"
  >
    <el-form :model="state.formItem" :rules="state.rules" ref="usersAddUpdateRef">
      <el-form-item label="账号" prop="us">
        <el-input v-model="state.formItem.us" placeholder="请输入账号"></el-input>
      </el-form-item>
      <el-form-item label="账号" prop="ps">
        <el-input v-model="state.formItem.ps" placeholder="请输入密码"></el-input>
      </el-form-item>
      <el-form-item label="性别" prop="sex">
        <el-radio-group v-model="state.formItem.sex">
          <el-radio :label="0">男</el-radio>
          <el-radio :label="1">女</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="状态" prop="state">
        <el-switch
          v-model="state.formItem.state"
          :active-value="1"
          :inactive-value="0"
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <div style="text-align: center;">
        <el-button @click="cancel">关闭</el-button>
        <el-button type="primary" :loading="state.loading" @click="ok">提交</el-button>
      </div>
    </template>
  </el-dialog>
</template>
<script>
import { defineComponent, reactive, ref, unref } from 'vue'
import { usersAdd } from '@/api/user'
import { ElMessage } from 'element-plus'
export default defineComponent({
  name: 'usersAddUpdate',
  emits:['reload'],
  setup(prop, context) {
    const usersAddUpdateRef = ref()
    // reactive定义多个数据的响应式
    const state = reactive({
      open: false,
      title: "用户添加",
      loading: false,
      formItem: {
        us: '',
        ps: '',
        sex: 0,
        state: 1
      },
      rules: {
        us: [{ required: true, message: "请输入账号", trigger: "blur" }],
        ps: [{ required: true, message: "请输入密码", trigger: "blur" }],
        sex: [{ required: true, message: "请选择性别", trigger: "change" }],
        state: [{ required: true, message: "请选择状态", trigger: "change" }],
      }
    })

    const cancel = () => {
      unref(usersAddUpdateRef).resetFields()
      state.open = false
    }

    const ok = () => {
      unref(usersAddUpdateRef).validate((valid) => {
        if (!valid) return
        state.loading = true
        usersAdd(state.formItem)
          .then((res) => {
            if (res.data.code === 200) {
              ElMessage.success('账号添加成功')
              state.open = false
              context.emit('reload')
            } else {
              state.loading = false
            }
          })
          .catch(() => {
            state.loading = false
          })
      })
    }

    return {
      state,
      cancel,
      ok,
      usersAddUpdateRef
    }
  }
})
</script>
